<?php
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\wework\listener;

use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;
use app\wework\model\BaseModel;
use app\wework\model\QrModel;
use think\facade\Log;

class CustomerQrCallback
{
    /**
     * 通过渠道活码添加客户监听 入口
     * @param $event 企微官方添加客户回调数据
     * @return 不可返回false
     */
    public function handle($event)
    {
        if(!array_key_exists("State",$event)){
            $this->addEt($event);
        }else{
            $qr = Db::table('kt_wework_qr')->where('state',$event['State'])->find();
            if($qr){
                $this->addCustomerByCode($event);
            }
        }
    }

    /**
     * 处理数据 
     * @param $event 企微官方添加客户回调数据
     * @return 不可返回false
     */
    private function addCustomerByCode($arr){
        $corpID = $arr['ToUserName'];//企业微信CorpID
        $qr = Db::table('kt_wework_qr')->json(['welcome_type','staffid','staff_data','staff_standby','staffup_data','tag','welcome_other_data','dayparting_data','welcom_shield','skipverify_time'])->where('state',$arr['State'])->find();
        $wid = $qr['wid'];
        $staff = Db::table('kt_wework_staff')->where(['wid'=>$qr['wid'],'userid'=>$arr['UserID']])->find();
        $customer = Db::table('kt_wework_customer')->where(['wid'=>$qr['wid'],'external_userid'=>$arr['ExternalUserID'],'staff_id'=>$staff['id']])->find();
        //记录
        $log = Db::table("kt_wework_scan_log")->where(["external_userid"=>$arr["ExternalUserID"],"pid"=>$qr["id"],"type"=>"qr"])->find();
        if(!$log){
            $log_data["external_userid"] = $arr["ExternalUserID"];
            $log_data["staff_id"] = $staff["id"];
            $log_data["pid"] = $qr["id"];
            $log_data["type"] = "qr";
            $log_data["create_time"] = date("Y-m-d H:i:s");
            Db::table("kt_wework_scan_log")->insertGetId($log_data);
        }
        //自动打标签
        if($qr['tag_status'] == 1){
            $addTag = $qr['tag'];
            $tagParam = [
                'userid' => $arr['UserID'],
                'external_userid' => $arr['ExternalUserID'],
                'add_tag' => $addTag,
                'remove_tag'=> [],
            ];
            if($addTag){
                $editEtTagRes = QyWechatApi::editMarkTag($tagParam,$wid);
                if($editEtTagRes["errcode"] == 0){
                    Db::table('kt_wework_customer')->where('id',$customer['id'])->json(['tags'])->save(['tags'=>$addTag]);
                }
            }
        }
        //修改客户备注信息
        $bzParam = [];
        $bz = [];
        if($qr['customerbz_status'] == 1){   //备注信息
            switch ($qr['customerbzqh_status']) {
                case '1':
                    $bzParam['remark'] = $qr['customerbz'].$customer['name'];
                    break;
                case '2':
                    $bzParam['remark'] = $customer['name'].$qr['customerbz'];
                    break;
            }
            $bz['remark'] = $bzParam['remark'];
        }
        if($qr['customerdes_status'] == 1)$bz['description'] = $bzParam['description'] = $qr['customerdes'];
        if($bzParam){
            $bzParam['userid'] = $arr['UserID'];
            $bzParam['external_userid'] = $arr['ExternalUserID'];
            $remark = QyWechatApi::externalcontactRemark($bzParam,$wid);
            if($remark['errcode'] == 0){
                Db::table('kt_wework_customer')->where('id',$customer['id'])->save($bz);
            }
        }
        //发送欢迎语
        if($arr['WelcomeCode'] && $qr["welcome_type"] == 1){
            $welParam["welcome_code"] = $arr['WelcomeCode'];
            $msg = '';
            $attachments = [];
            if($qr['dayparting_status'] == 1){      //分时段欢迎语是否开启                
                $week = date('w');
                foreach ($qr['dayparting_data'] as $dayparting) {   //遍历分时段数据
                   if(in_array($week, $dayparting["week_arr"]) && time() >= strtotime($dayparting['startime']) && time() <= strtotime($dayparting['endtime'])){
                        $msg = $dayparting['welcome_content'];
                        if(count($dayparting['welcome_other_data']) > 0){
                           $attachments = $this->assembleOther($dayparting['welcome_other_data'],$wid);
                        }
                        break;
                   }
                }
            }
            //判断分时段是否存在适用的欢迎语,不存在则用默认渠道欢迎语
            if(!$msg && !$attachments){  
                $msg = $qr['welcome_content'];
                if(count($qr['welcome_other_data'])>0){
                    $attachments = $this->assembleOther($qr['welcome_other_data'],$wid);
                }
            }
            if($msg){
                    $msg = str_replace('[插入客户昵称]', $customer['name'], $msg);
                    $msg = str_replace('<div>', '
', $msg);
                    $msg = str_replace('&nbsp;', ' ', $msg);
                    $msg = str_replace('<br>', '', $msg);
                    $msg = str_replace('</div>', '', $msg);
                    $msg = str_replace('amp;', '', $msg);
                $welParam['text'] = [
                    'content'=>$msg,
                ];

            }
            Log::error($welParam);
            if($attachments) $welParam['attachments'] = $attachments;
            $res = QyWechatApi::sendWelcomeMsg($wid, $welParam);
        
            Log::error($res);
        }
    }

    //组装 换迎语附件 数据
    private function assembleOther($otherData,$wid){
        $data = [];
        foreach ($otherData as $other) {
            switch ($other['type']) {
                case '1':
                    $data[] = [
                        'msgtype'=>'image',
                        'image'=>[
                            'media_id' => QyWechatApi::mediaUpload($wid,$other['url'],'image')['media_id'],
                        ]
                    ];
                    break;
                case '2':
                    $data[] = [
                        'msgtype'=>'link',
                        'link'=>[
                            'title' => $other['title'],
                            'picurl' => $other['link_picurl'],
                            'desc' => $other['link_desc'],
                            'url' => $other['link_url'],
                        ]
                    ];
                    break;
                case '3':
                    $data[] = [
                        'msgtype'=>'miniprogram',
                        'miniprogram'=>[
                            'title' => $other['title'],
                            'pic_media_id' => QyWechatApi::mediaUpload($wid,$other['imageurl'],'image')['media_id'],
                            'appid' => $other['appid'],
                            'page' => $other['path'],
                        ]
                    ];
                    break;
            }
        }
        return $data;
    }

    private function addEt($arr){
        $corpID = $arr['ToUserName'];//企业微信CorpID
        $config = Db::table('kt_wework_config')->where(['corp_id'=>$corpID])->find();
        $wid = $config["wid"];
        $staff = Db::table('kt_wework_staff')->where(['wid'=>$config['wid'],'userid'=>$arr['UserID']])->find();
        $welcomemsg = Db::table('kt_wework_welcomemsg')->where(['wid'=>$config['wid']])->where('staffstr', 'like', "%\"{$staff["id"]}\"%]")->json(["staffer","adjunct_data","dayparting_data","content"])->find();
        $customer = Db::table('kt_wework_customer')->where(['wid'=>$wid,'external_userid'=>$arr['ExternalUserID'],'staff_id'=>$staff['id']])->find();
        $customer_info_res = QyWechatApi::getExternalDetail($wid,$arr["ExternalUserID"]);
        foreach($customer_info_res['follow_user'] as $follow_user){
            if($arr["UserID"] == $follow_user['userid']){
                $remark_mobiles = $follow_user["remark_mobiles"];
                $add_way = $follow_user['add_way'];
                if($add_way == 2){
                    //搜索手机号添加
                    $batch = Db::table('kt_wework_batch_addcus_info')->where(['wid'=>$wid,'phone'=>$remark_mobiles,'staffid'=>$staff["id"]])->find();
                    if($batch){
                        Db::table('kt_wework_batch_addcus_info')->where(['wid'=>$wid,'phone'=>$remark_mobiles,'staffid'=>$staff["id"]])->update(["add_status"=>1,"add_time"=>date("Y-m-d H:i:s")]);
                        if($batch["remarks"]){
                            $param = ['userid'=>$arr['UserID'],'external_userid'=>$arr['ExternalUserID'],'remark'=>$batch["remarks"]];
                            $res = QyWechatApi::externalcontactRemark($param,$wid);
                            if($res["errcode"] == 0){
                                Db::table('kt_wework_customer')->where(['wid'=>$wid,'external_userid'=>$arr['ExternalUserID'],'staff_id'=>$staff['id']])->update(["remark"=>$batch["remarks"]]);
                            }
                        }
                    }
                }
            }
        }
        $msg = '';
        $attachments = [];
        if(!$welcomemsg) return "无数据";
        //分时段欢迎语是否开启
        if($welcomemsg['dayparting_status'] == 1){
            $week = date('w');
            //遍历分时段数据
            foreach ($welcomemsg['dayparting_data'] as $dayparting) {
               if(in_array($week, $dayparting["week_arr"]) && time() >= strtotime($dayparting['startime']) && time() <= strtotime($dayparting['endtime'])){
                    $msg = $dayparting['welcome_content'];
                    if(count($dayparting['welcome_other_data']) > 0){
                       $attachments = $this->assembleOther($dayparting['welcome_other_data'],$wid);
                    }
                    break;
               }
            }
        }
        //判断是否在分时段欢迎语内，不在则执行
        if(!$msg && !$attachments){  
            $msg = $welcomemsg['content'];
            if($welcomemsg['adjunct_data']){
                $attachments = $this->assembleOther($welcomemsg['adjunct_data'],$wid);
            }
        }
        if($msg){
            $msg = str_replace('[插入客户昵称]', $customer['name'], $msg);
            $msg = str_replace('<div>', '
', $msg);
            $msg = str_replace('&nbsp;', ' ', $msg);
            $msg = str_replace('<br>', '', $msg);
            $msg = str_replace('</div>', '', $msg);
            $msg = str_replace('amp;', '', $msg);
            $welParam['text'] = [
                'content'=>$msg,
            ];
        }
        $welParam['welcome_code'] = $arr['WelcomeCode'];
        if($attachments) $welParam['attachments'] = $attachments;
        QyWechatApi::sendWelcomeMsg($wid, $welParam);
    }

}
